package com.qire.common;

import android.app.Activity;
import android.content.Context;

import androidx.multidex.MultiDexApplication;

import com.bumptech.glide.Glide;
import com.qire.antsdeeplink.AntsDeepLink;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.lifecycleHandler.ActivityLifecycleHandler;
import com.qire.common.collect.SafeIterableList;
import com.qire.common.collect.SafeIterableList.Node;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.utils.CacheStorageUtil;
import com.qire.common.utils.EquipmentInfoUtil;

/**
 * Application 实例，用于全局使用和监听，由于现在的合规审查特别严格，故不应该图省事在这里做第三方sdk和一些权限的初始化操作。
 * 需要用户同意后在做操作，故提出 {@link InitManage} 作为专门管理初始化的操作工具。所有的初始化操作应该也必须想办法在哪里完成。
 */
public class SummerApp extends MultiDexApplication {

    private static SummerApp summerApp;
    public static SummerApp summerApp() {
        return summerApp;
    }

    @Override
    public void onCreate() {
        summerApp = this;

        // 这两个初始化很重要，属于系统框架级别的初始化，会有大量映射表加载，
        // 存在IO操作可能会影响启动，可以在后期使用多线程调整
        AntsRouter.init(this);

        AntsDeepLink.DISPATCHER.init(this);

        super.onCreate();

        // 屏幕像素度量单位初始化
        EquipmentInfoUtil.init(this);

        // 初始化缓存工具，大部分需要行为需要依赖缓存，固应该优先执行初始化
        CacheStorageUtil.init(this);

        // 用户数据本地加载缓存
        UserEntity.self.loadLocalUserInfo();

        // 应用前后台切换监听
        registerActivityLifecycleCallbacks(appFrontBackStateListener);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if(level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory();
        }
        Glide.get(this).trimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).onLowMemory();
    }

    /** app 前后台状态切换监听 */
    private final AppFrontBackStateListener appFrontBackStateListener = new AppFrontBackStateListener();

    /** APP 激活\失活 注册器列表 */
    private final SafeIterableList<AppActiveRegistrar> receiverList = new SafeIterableList<>();

    /** 添加注册器，如果已经在激活状态会直接调用注册器的注册行为，否则会等待APP被激活时才调用 */
    public void addActiveRegistrar(AppActiveRegistrar registrar) {
        receiverList.add(registrar);
        if(appFrontBackStateListener.isActive) {
            registrar.registerReceiver(this);
        }
    }

    /** 注册 */
    private void registerReceiver() {
        for(Node<AppActiveRegistrar> registrarNode : receiverList) {
            AppActiveRegistrar registrar = registrarNode.value();
            if(registrar != null) {
                registrar.registerReceiver(this);
            }
        }
    }

    /** 注销 */
    private void unregisterReceiver() {
        for(Node<AppActiveRegistrar> registrarNode : receiverList) {
            AppActiveRegistrar registrar = registrarNode.value();
            if(registrar != null) {
                registrar.unregisterReceiver(this);
            }
        }
    }

    /** Activity 生命周期监听，用于监控app前后台状态切换 */
    public class AppFrontBackStateListener extends ActivityLifecycleHandler {

        /** 当前Activity个数 */
        private int activityNumber = 0;

        /** APP的激活状态，true表示激活，false表示退出失活 */
        private volatile boolean isActive = false;

        private AppFrontBackStateListener() {}

        private void onEnteredAppForeground() {
            isActive = true;
            // App just entered the foreground. Do something here!
            registerReceiver();
        }

        private void onEnteredAppBackground() {
            isActive = false;
            // App just entered the background. Do something here!
            unregisterReceiver();
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (activityNumber == 0) {
                // app回到前台
                onEnteredAppForeground();
            }
            activityNumber++;
        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityNumber--;
            if (activityNumber == 0) {
                // app回到后台
                onEnteredAppBackground();
            }
        }
    }

    /** App 激活状态注册器，用于需要在APP激活时打开，失活时关闭的相关功能注册 */
    public interface AppActiveRegistrar {
        void registerReceiver(Context context);
        void unregisterReceiver(Context context);
    }

}